package com.sxt.practiceapplication.pager;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.cache.CacheMode;
import com.lzy.okhttputils.callback.StringCallback;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.sxt.practiceapplication.R;
import com.sxt.practiceapplication.activities.ChangePasswordActivity;
import com.sxt.practiceapplication.activities.LoginActivity;
import com.sxt.practiceapplication.base.BasePager;
import com.sxt.practiceapplication.common.Constants;
import com.sxt.practiceapplication.common.ServerStatus;
import com.sxt.practiceapplication.common.Urls;
import com.sxt.practiceapplication.databinding.MineLayoutBinding;
import com.sxt.practiceapplication.databinding.UserInfoLayoutBinding;
import com.sxt.practiceapplication.entity.user.LoginData;
import com.sxt.practiceapplication.entity.user.UserQuery;
import com.sxt.practiceapplication.entity.user.data.UserQueryData;
import com.sxt.practiceapplication.utils.GsonBinder;
import com.sxt.practiceapplication.utils.LoginUser;
import com.sxt.practiceapplication.utils.ToastUtils;
import com.sxt.practiceapplication.utils.Tools;
import com.sxt.practiceapplication.view.InfoItemView;

import okhttp3.Call;
import okhttp3.Response;

public class MinePager extends BasePager implements InfoItemView.OnClickListener, View.OnClickListener {

    private MineLayoutBinding mineLayoutBinding;

    private UserInfoLayoutBinding userInfoLayoutBinding;

    private UserQuery userQuery;

    private LoginData userData;


    public MinePager(Context context) {
        super(context);
    }

    @Override
    protected void initContent(FrameLayout content) {
        content.removeAllViews();
        mineLayoutBinding = MineLayoutBinding.inflate(LayoutInflater.from(context));
        userInfoLayoutBinding = UserInfoLayoutBinding.inflate(LayoutInflater.from(context));
        content.addView(mineLayoutBinding.getRoot());
        addClickListener();
        registerLoginStateChangeBroadcast();
    }

    private void addClickListener() {
        mineLayoutBinding.favorite.setOnInfoItemViewClickListener(this);
        mineLayoutBinding.buttonLogout.setOnClickListener(this);
        mineLayoutBinding.mineInfo.setOnClickListener(this);
        mineLayoutBinding.changePassword.setOnClickListener(this);

        userInfoLayoutBinding.toMine.setOnClickListener(this);
        userInfoLayoutBinding.nickname.setOnInfoItemViewClickListener(this);
        userInfoLayoutBinding.sex.setOnInfoItemViewClickListener(this);
        userInfoLayoutBinding.tel.setOnInfoItemViewClickListener(this);
        userInfoLayoutBinding.email.setOnInfoItemViewClickListener(this);
    }

    @Override
    public void doInitData() {
        //设置标题
        headTitle.setText(R.string.mine_title);
        queryUser();
    }

    /**
     * InfoItemView 的点击事件
     *
     * @param view InfoItemView
     */
    @SuppressWarnings("deprecation")
    @Override
    public void onClick(InfoItemView view) {
        if(userQuery == null) {
            return;
        }
        if (view == mineLayoutBinding.favorite) {
            ToastUtils.show("功能开发中");
        } else if (view == userInfoLayoutBinding.nickname) {
            CharSequence nickname = view.getInfoValue().getText();
            QMUIDialog.EditTextDialogBuilder dialogBuilder = new QMUIDialog.EditTextDialogBuilder(context);
            dialogBuilder.setTitle("昵称")
                    .setPlaceholder("请输入昵称")
                    .setDefaultText(nickname.equals("请设置昵称") ? null : nickname)
                    .addAction("确认", (dialog, index) -> updateUser(dialog,
                            userQuery.setNickname(
                                    dialogBuilder
                                            .getEditText()
                                            .getText()
                                            .toString())))
                    .show();
        } else if (view == userInfoLayoutBinding.sex) {
            CharSequence sex = view.getInfoValue().getText();
            new QMUIDialog.CheckableDialogBuilder(context)
                    .addItems(new String[]{"男", "女"}, (dialog, which) -> updateUser(dialog,
                            userQuery.setSex(which == 0 ? "男" : which == 1 ? "女" : null)))
                    .setCheckedIndex(sex.equals("男") ? 0 : sex.equals("女") ? 1 : -1)
                    .show();
        } else if (view == userInfoLayoutBinding.tel) {
            QMUIDialog.EditTextDialogBuilder dialogBuilder = new QMUIDialog.EditTextDialogBuilder(context);
            dialogBuilder.setTitle("电话")
                    .setPlaceholder("请输入电话")
                    .setDefaultText(view.getInfoValue().getText())
                    .addAction("确认", (dialog, index) -> updateUser(dialog,
                            userQuery.setTel(
                                    dialogBuilder
                                            .getEditText()
                                            .getText()
                                            .toString())))
                    .show();
        } else if (view == userInfoLayoutBinding.email) {
            QMUIDialog.EditTextDialogBuilder dialogBuilder = new QMUIDialog.EditTextDialogBuilder(context);
            dialogBuilder.setTitle("邮箱")
                    .setPlaceholder("请输入邮箱")
                    .setDefaultText(view.getInfoValue().getText())
                    .addAction("确认", (dialog, index) -> updateUser(dialog,
                            userQuery.setEmail(
                                    dialogBuilder
                                            .getEditText()
                                            .getText()
                                            .toString())))
                    .show();
        }
    }

    /**
     * 更新用户信息
     *
     * @param dialog     弹出框框
     * @param updateUser 更新后的用户对象
     */
    private void updateUser(DialogInterface dialog, UserQuery updateUser) {
        OkHttpUtils.put(Urls.USER_UPDATE_URL + userData.getUserId() + "/")
                .tag(this)
                .cacheMode(CacheMode.NO_CACHE)
                .headers("Authorization", userData.getToken())
                .upJson(GsonBinder.toJsonStr(updateUser))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        context.sendBroadcast(new Intent(Constants.LOGIN_STATE_CHANGE));
                        dialog.dismiss();
                    }
                });
    }

    /**
     * 一般view都适用的点击事件
     *
     * @param view View
     */
    @Override
    public void onClick(View view) {
        if (view == mineLayoutBinding.mineInfo) {
            if (isLogin()) {
                content.removeAllViews();
                content.addView(userInfoLayoutBinding.getRoot());
            } else {
                context.startActivity(new Intent(context, LoginActivity.class));
            }
        } else if (view == mineLayoutBinding.buttonLogout) {
            if (isLogin()) {
                LoginUser.logout(context);
            } else {
                context.startActivity(new Intent(context, LoginActivity.class));
            }
        } else if (view == userInfoLayoutBinding.toMine) {
            content.removeAllViews();
            content.addView(mineLayoutBinding.getRoot());
        } else if (view == mineLayoutBinding.changePassword) {
            context.startActivity(new Intent(context, ChangePasswordActivity.class));
        }
    }

    private boolean isLogin() {
        return LoginUser.isLogin(context);
    }

    private void queryUser() {
        if (isLogin()) {
            if (userData == null) {
                userData = LoginUser.getCurrentUserData(context);
            }
            OkHttpUtils.get(Urls.USER_QUERY_URL + userData.getUserId())
                    .tag(this)
                    .cacheMode(CacheMode.NO_CACHE)
                    .headers("Authorization", userData.getToken())
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String result, Call call, Response response) {
                            UserQueryData userQueryData = GsonBinder.toObj(result, UserQueryData.class);
                            if (userQueryData.getCode().equals(ServerStatus.SUCCESS.getCode())) {
                                userQuery = userQueryData.getData();
                                if (userQuery != null) {
                                    mineLayoutBinding.username.setText(userQuery.getNickname());
                                    userInfoLayoutBinding.account.getInfoValue().setText(userQuery.getUsername());
                                    userInfoLayoutBinding.nickname.getInfoValue().setText(userQuery.getNickname());
                                    userInfoLayoutBinding.sex.getInfoValue().setText(userQuery.getSex());
                                    userInfoLayoutBinding.email.getInfoValue().setText(userQuery.getEmail());
                                    userInfoLayoutBinding.tel.getInfoValue().setText(userQuery.getTel());
                                }
                            } else if (userQueryData.getCode().equals(ServerStatus.AUTH_ERROR.getCode())) {
                                Tools.showErrorDialog(context, userQueryData.getMessage());
                                LoginUser.logout(context);
                            }
                        }
                    });
        } else {
            mineLayoutBinding.username.setText("请登录");
            mineLayoutBinding.buttonLogout.setVisibility(View.INVISIBLE);
            mineLayoutBinding.changePassword.setVisibility(View.INVISIBLE);
        }
    }

    private void registerLoginStateChangeBroadcast() {
        ((Activity) context).registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (isLogin()) {
                    userData = LoginUser.getCurrentUserData(context);
                    queryUser();
                    mineLayoutBinding.buttonLogout.setVisibility(View.VISIBLE);
                    mineLayoutBinding.changePassword.setVisibility(View.VISIBLE);
                } else {
                    userData = null;
                    userQuery = null;
                    mineLayoutBinding.buttonLogout.setVisibility(View.INVISIBLE);
                    mineLayoutBinding.changePassword.setVisibility(View.INVISIBLE);
                    mineLayoutBinding.username.setText("请登录");
                }
            }
        }, new IntentFilter(Constants.LOGIN_STATE_CHANGE));
    }

}
